<?php

/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/3/5
 * Time: 14:27
 */

namespace app\home\controller;

use app\admin\model\MessageTemplate;
use app\home\model\AmountLog;
/*use app\home\model\BargainingOrder;*/
use app\home\model\Config;
use app\home\model\GoodsOrder;
use app\home\model\IntegralLog;
use app\home\model\Level;
use app\home\model\Recharge;
use app\home\model\UserCommission;
use app\home\model\UserCoupon;
use app\home\model\UserPackage;
use app\home\model\UserToken;
use app\merchant\model\PackageOrder;
use app\merchant\model\UserConsumption;
use app\services\jwt\JwtService;
use app\services\wechat\Miniprogram;
use app\services\wechat\Offiaccount;
use think\Exception;
use think\Request;
use  app\home\model\User;
use WeChatPay\Crypto\AesGcm;
use WeChatPay\Crypto\Rsa;
use WeChatPay\Formatter;

class Wechat
{
    public function rand_str($number){
        $str = '';
        for ($i=0;$i < $number;$i++){
            $str .=  mt_rand(0,9);

        }

        $user = new User();
        $userInfo = $user->where(['random_code' => $str])->find();
        if ($userInfo){
            $this->rand_str();
        }
        return  $str;
    }

    /**
     * 微信登录
     * @param Request $request
     * @throws \think\Exception
     */
    public function wechatLogin(Request $request)
    {
        $param = $request->param();

        $Offiaccount = new Offiaccount();
        if (isset($param['code'])) {

            $userWechatInfo = $Offiaccount->get_user_info($param['code']);
            $userDate['openid'] = $userWechatInfo['openid']; //数据openid
            $userDate['unionid'] = $userWechatInfo['unionid']; //数据unionid
            $userDate['wachat_nickname'] = $userWechatInfo['nickname']; //数据unionid
            $userDate['nickname'] = $userWechatInfo['nickname'];
            $userDate['avatar'] = $userWechatInfo['headimgurl']; //数据unionid
            $userModel = new User();
            $userByPhone = $userModel->where(['openid' => $userDate['openid']])->find();//
            if ($userByPhone) {
                if ($userByPhone['status'] != 1) {
                    return error("账号未启用,请联系管理员", [], '204');
                }
                $userDate['last_login_ip'] = request()->ip();
                $userDate['last_login_time'] = time();
                $userModel->where(['id' => $userByPhone['id']])->update($userDate);
                $id = $userByPhone['id'];
            } else {
                $userInfo = $userModel->where($userDate)->find();
                if (empty($userInfo)) {
                    $levelModel = new Level();
                    $levelInfo = $levelModel->order('consumption_amount', 'asc')->find();
                    $userDate['register_ip'] = request()->ip();
                    $userDate['level_id'] = $levelInfo['id'];
                    $userDate['level_name'] = $levelInfo['name'];
                    $userDate['create_time'] = time();
                    $userDate['nickname'] = $userWechatInfo['nickname'];
                    $userDate['random_code'] = $this->rand_str(12);
                    $userDate['invite_code'] = $this->getRandCode(6);
                    if (isset($param['invite']) ){
                        $puserInfo = $userModel->where(['invite_code' => $param['invite']])->find();
                        if ($puserInfo){
                            $userDate['pid']= $puserInfo['id'];
                            $userDate['pids']= $puserInfo['pids'].','.$puserInfo['id'];
                        }else{
                            return  error('分享链接有误');
                        }
                    }
                    $userModel->insert($userDate);
                    $id = $userModel->getLastInsID();
                    $userModel->updateUserLevel($id, 0);
                } else {
                    $userDate['last_login_ip'] = request()->ip();
                    $userDate['last_login_time'] = time();
                    $userModel->where(['id' => $userByPhone['id']])->update($userDate);
                    $id = $userInfo['id'];
                }
            }
            $jwt = new JwtService();
            //根据用户id生成token
            $token = $jwt->getToken($id, 30);  //获取token
            $tokenConfig = ['uid' => $id, 'token' => $token, 'create_time' => time(),
                'effective_time' => time() + 60 * 60 * 24 * 30, 'login_ip' => $request->ip(), 'type' => 1];  //token配置信息  //token配置信息
            $tokenModel = new UserToken();
            $user = $userModel->where(['id' => $id])->find();
            $tokenModel->insert($tokenConfig);  //更新token
            $user['token'] = $token;
            //H5/index.html
            $url = getProtocol() . $_SERVER["HTTP_HOST"];

            if (isset($param['currentIndex'])){
                $url =  $url .'/'. $param['url'] . "?id=" . $id.'&currentIndex='.$param['currentIndex'] ;
            }else{
                $url = $url  .'/'. $param['url'] . "?id=" . $id;
            }
          /*  if (isset($param['store_id'])){
                $url =  $url  . '&store_id='.$param['store_id'];
            }
            if (isset($param['homehtml'])){
                $url =  $url  . '#/pages/storePaymentCode/storePaymentCode';
            }*/
            Header("Location: " . $url );
            die;
        } else {
            $codeUrl = $Offiaccount->getWechatAuthCode();

            Header("Location: $codeUrl");
            die;
        }

    }
    public function goodsNotify()
    {
        $getCallBackJson = file_get_contents('php://input');
        file_put_contents('./log/' . date('Y-m-d') . 'goodsdata.txt', $getCallBackJson . PHP_EOL, FILE_APPEND);
        $getCallBackArray = json_decode($getCallBackJson, true);
        $associatedData = $getCallBackArray['resource']['associated_data'];
        $nonceStr = $getCallBackArray['resource']['nonce'];
        $ciphertext = $getCallBackArray['resource']['ciphertext'];

        $ciphertext = \base64_decode($ciphertext);
        $ctext = substr($ciphertext, 0, -16);
        $authTag = substr($ciphertext, -16);
        $str = \openssl_decrypt($ctext, 'aes-256-gcm', Config::getConfigValue('apikey'), \OPENSSL_RAW_DATA, $nonceStr, $authTag, $associatedData);
        $result = json_decode($str, true);;
        if ($result['trade_state'] == 'SUCCESS') {
            $out_trade_no = $result['out_trade_no'];
            $pay_money = bcdiv($result['amount']['total'], 100, 2);
            $goodsOrder = new  GoodsOrder();
            $goodsOrderInfo = $goodsOrder->where(['sn_order' => $out_trade_no])->find();
            if ($pay_money !=$goodsOrderInfo['reality_amount'] ){
                return \json([
                    "code" => "FAIL",
                    "message" => "支付金额有误"
                ]);
            }
            if ($goodsOrderInfo['status'] != 1) {
                return \json([
                    "code" => "FAIL",
                    "message" => "失败"
                ]);
            }
            $goodsOrder->where(['sn_order' => $out_trade_no])->update(['status' => 2]);
            $userModel = new User();
            $userInfo = $userModel->where(['id' => $goodsOrderInfo['user_id']])->find();
            try {
               $goodsOrder->startTrans();
                $amountLog = new AmountLog();
                $amountLog->insert([
                    'amount' => $pay_money,
                    'pay_method' => 1,
                    'order_id' => $goodsOrderInfo['id'],
                    'operate_type' => 8,
                    'pay_type' => 3,
                    'create_time' => time(),
                    'ratio' => 1,
                    'uid' => $goodsOrderInfo['user_id'],
                    'type' => 2,
                    'order_sn' => $goodsOrderInfo['sn_order'],
                    'status' => 0,
                ]);
                if ($goodsOrderInfo['take_over_way'] == 2) {
                    $goodsOrder->where(['sn_order' => $out_trade_no])->update(['status' => 3, 'update_time' => time()]);
                } else {
                    $goodsOrder->where(['sn_order' => $out_trade_no])->update(['status' => 4, 'update_time' => time()]);
                }
                 $goodsOrder->commit();
                $messageModel = new MessageTemplate();
                $messageModel->sendMessage($userInfo['openid'], [
                    'thing1' => ['value' =>  substr($goodsOrderInfo['goods_name'], 0, 18)],
                    'amount7' => ['value' => $goodsOrderInfo['reality_amount']],
                    'thing8' => ['value' => '微信支付'],
                    'date3' => ['value' => date('Y-m-d H:i')]], 'buy_goods');
            } catch (Exception $exception) {
                $goodsOrder->rollback();
                file_put_contents('./' . date('Y-m-d') . 'paylogerror.txt', $exception->getMessage() . PHP_EOL, FILE_APPEND);
                $goodsOrder->where(['sn_order' => $out_trade_no])->update(['status' => 1]);
                return \json([
                    "code" => "FAIL",
                    "message" => "失败"
                ]);
            }
            return \json([
                "code" => "SUCCESS",
                "message" => "成功"
            ]);
        }
    }
    public function polymerizationNotify()
    {
        $getCallBackJson = file_get_contents('php://input');
        file_put_contents('./log/' . date('Y-m-d') . 'userConsumption.txt', $getCallBackJson . PHP_EOL, FILE_APPEND);
        $getCallBackArray = json_decode($getCallBackJson, true);
        $associatedData = $getCallBackArray['resource']['associated_data'];
        $nonceStr = $getCallBackArray['resource']['nonce'];
        $ciphertext = $getCallBackArray['resource']['ciphertext'];
        $ciphertext = \base64_decode($ciphertext);
        $ctext = substr($ciphertext, 0, -16);
        $authTag = substr($ciphertext, -16);
        $str = \openssl_decrypt($ctext, 'aes-256-gcm', Config::getConfigValue('apikey'), \OPENSSL_RAW_DATA, $nonceStr, $authTag, $associatedData);
        $result = json_decode($str, true);;
        if ($result['trade_state'] == 'SUCCESS') {
            $out_trade_no = $result['out_trade_no'];
            $pay_money = bcdiv($result['amount']['total'], 100, 2);
            $UserConsumption = new  UserConsumption();
            $UserConsumptionInfo = $UserConsumption->where(['sn_order' => $out_trade_no])->find();
            if ($pay_money !=$UserConsumptionInfo['amount'] ){
                return \json([
                    "code" => "FAIL",
                    "message" => "支付金额有误"
                ]);
            }
            if ($UserConsumptionInfo['status'] != 1) {
                return \json([
                    "code" => "FAIL",
                    "message" => "失败"
                ]);
            }
            $UserConsumption->where(['sn_order' => $out_trade_no])->update(['status' => 2]);
                $UserConsumption->startTrans();
                $amountLog = new AmountLog();
                $amountLog->insert([
                    'amount' => $pay_money,
                    'pay_method' => 1,
                    'order_id' => $UserConsumptionInfo['id'],
                    'operate_type' => 29,
                    'pay_type' => 5,
                    'create_time' => time(),
                    'ratio' => 1,
                    'uid' => 0,
                    'type' => 2,
                    'order_sn' => $UserConsumptionInfo['sn_order'],
                    'status' => 1,
                    'store_id' => $UserConsumptionInfo['store_id'],
                    'is_polymerization' => 1
                ]);
                $UserConsumption->where(['sn_order' => $out_trade_no])->update(['status' => 3, 'update_time' => time()]);
                $UserConsumption->commit();

            return \json([
                "code" => "SUCCESS",
                "message" => "成功"
            ]);
        }
    }
    public function packageNotify(Request $request)
    {
        $getCallBackJson = file_get_contents('php://input');
        file_put_contents('./log/'  . date('Y-m-d') . 'package.txt', $getCallBackJson . PHP_EOL, FILE_APPEND);
        $getCallBackArray = json_decode($getCallBackJson, true);
        $associatedData = $getCallBackArray['resource']['associated_data'];
        $nonceStr = $getCallBackArray['resource']['nonce'];
        $ciphertext = $getCallBackArray['resource']['ciphertext'];
        $ciphertext = \base64_decode($ciphertext);
        $ctext = substr($ciphertext, 0, -16);
        $authTag = substr($ciphertext, -16);
        $str = \openssl_decrypt($ctext, 'aes-256-gcm', Config::getConfigValue('apikey'), \OPENSSL_RAW_DATA, $nonceStr, $authTag, $associatedData);
        $result = json_decode($str, true);;
        if ($result['trade_state'] == 'SUCCESS') {
            $out_trade_no = $result['out_trade_no'];
            $pay_money = bcdiv($result['amount']['total'], 100, 2);
            $packageOrderModel = new PackageOrder();
            $packageInfo = $packageOrderModel->where(['order_sn' => $out_trade_no])->find();
            if ($packageInfo['status'] = !1) {
                return \json([
                    "code" => "FAIL",
                    "message" => "失败"
                ]);
            }
            $packageOrderModel->where(['order_sn' => $out_trade_no])->update(['status' => 2]);
            try {
                $packageOrderModel->startTrans();
                $userModel = new User();
                $userInfo = $userModel->where(['id' => $packageInfo['uid']])->find();
                $consumptionAmount = bcadd($userInfo['consumption_amount'], $pay_money, 2);

                $userModel->inc('integral',$packageInfo['get_integral'])
                    ->inc('package_num')
                    ->inc('consumption_amount', $pay_money)
                    ->inc('surplus_integral', $packageInfo['get_integral'])
                    ->where(['id' => $packageInfo['uid']])
                    ->update(); // 修改用户数据
                $userModel->updateUserLevel($userInfo['id'], $consumptionAmount);
                if ($packageInfo['get_integral'] > 0) {
                    $integralLog = new IntegralLog();
                    $integralLog->insert([
                        'uid' => $packageInfo['uid'],
                        'type' => 1,
                        'num' => $packageInfo['get_integral'],
                        'deduction_ratio' => $packageInfo['get_integral_ratio'],
                        'mode_type' => 4,
                        'order_id' => $packageInfo['id'],
                        'create_time' => time()
                    ]);
                }
                $amountLog = new AmountLog();
                $amountLog->insert([
                    'amount' => $pay_money,
                    'pay_method' => 1,
                    'order_id' => $packageInfo['id'],
                    'operate_type' => 10,
                    'pay_type' => 3,
                    'create_time' => time(),
                    'ratio' => 1,
                    'uid' => $packageInfo['uid'],
                    'type' => 2,
                    'order_sn' => $packageInfo['order_sn'],
                ]);
                $userPackageModel = new UserPackage();
                $userPackageData = [
                    'package_id' => $packageInfo['package_id'],
                    'uid' => $packageInfo['uid'],
                    'num' => $packageInfo['number'] + $packageInfo['give_number'],
                    'total_num' => $packageInfo['number'] + $packageInfo['give_number'],
                    'create_time' => time(),
                    'order_id' => $packageInfo['id'],
                ];
                $userPackageModel->insert($userPackageData);
                $packageOrderModel->where(['order_sn' => $out_trade_no])->update([
                    'status' => 3,
                    'update_time' => time(),
                    'pay_time' => time(),
                ]);
                $distribution_level = Config::getConfigValue('distribution_level');
                $firstCommissionData = [];
                $secondCommissionData = [];
                if ($distribution_level > 0) {
                    if ($userInfo['pid'] > 0) {
                        $first_commission = Config::getConfigValue('first_commission');
                        if ($first_commission > 0) {
                            $pUserInfo = $userModel->where(['id' => $userInfo['pid']])->find();
                            $userCommissionModel = new UserCommission();
                            $firstCommissionData = [
                                'trigger_uid' => $userInfo['id'],
                                'receive_uid' => $userInfo['pid'],
                                'level' => 1,
                                'amount' => bcdiv(bcmul($packageInfo['price'], $first_commission, 2),100, 2),
                                'ratio' => $first_commission,
                                'order_id' => $out_trade_no,
                                'create_time' => time(),
                                'type' => 2,
                            ];
                            $userCommissionModel->insert($firstCommissionData);
                            $userModel->where(['id' => $userInfo['pid']])
                                ->inc('total_commission', bcdiv(bcmul($first_commission, $packageInfo['price'], 2),100, 2))
                                ->inc('surplus_commission', bcdiv(bcmul($first_commission, $packageInfo['price'], 2),100, 2))
                                ->update();
                        }
                        if ($distribution_level >= 2) {
                            $second_commission = Config::getConfigValue('second_commission');
                            if ($pUserInfo['pid'] > 0 && $second_commission > 0) {
                                $ppUserInfo = $userModel->where(['id' => $pUserInfo['pid']])->find();
                                $userCommissionModel = new UserCommission();
                                $secondCommissionData = [
                                    'trigger_uid' => $userInfo['id'],
                                    'receive_uid' => $pUserInfo['pid'],
                                    'level' => 2,
                                    'amount' =>bcdiv( bcmul($packageInfo['price'], $second_commission, 2),100, 2),
                                    'ratio' => bcdiv(bcmul($second_commission, 100, 2),100, 2),
                                    'order_id' => $out_trade_no,
                                    'create_time' => time(),
                                    'type' => 2,
                                ];
                                $userCommissionModel->insert();
                                $userModel->where(['id' => $pUserInfo['pid']])
                                    ->inc('total_commission', bcdiv( bcmul($second_commission, $packageInfo['price'], 2),100, 2))
                                    ->inc('surplus_commission', bcdiv( bcmul($second_commission, $packageInfo['price'], 2),100, 2))
                                    ->update();
                            }
                        }
                    }
                }
                $packageOrderModel->commit();
                $messageModel = new MessageTemplate();
                if ($firstCommissionData) { // 一级分佣
                    $messageModel->sendMessage($pUserInfo['openid'], [
                        'thing2' => ['value' => '直推佣金'],
                        'amount8' => ['value' =>$firstCommissionData['amount']],
                        'amount6' => ['value' => bcadd($pUserInfo['surplus_commission'], $firstCommissionData['amount'], 2)],
                        'time4' => ['value' => date('Y-m-d H:i')]], 'commission_add'); //
                }
                if ($secondCommissionData) { // 一级分佣
                    $messageModel->sendMessage($ppUserInfo['openid'], [
                        'thing2' => ['value' => '间推佣金'],
                        'amount8' => ['value' => $secondCommissionData['amount']],
                        'amount6' => ['value' => bcadd($ppUserInfo['surplus_commission'], $secondCommissionData['amount'], 2)],
                        'time4' => ['value' => date('Y-m-d H:i')],
                    ], 'commission_add'); //
                }

                $messageModel->sendMessage($userInfo['openid'], [
                    'thing2' => ['value' => $packageInfo['name']],
                    'amount3' => ['value' => $packageInfo['price']],
                    'thing9' => ['value' => date('Y-m-d  H:i:s')],

                ], 'buy_package'); // 购买套餐卡
                if ( $packageInfo['get_integral']) {  // 积分变动
                    $messageModel->sendMessage($userInfo['openid'], [
                        'thing2' => ['value' => '积分'],
                        'amount8' =>['value' =>  $packageInfo['get_integral'].'分'],
                        'amount6' => ['value' => bcadd($userInfo['surplus_integral'],  $packageInfo['get_integral'],2)],
                        'time4' =>['value' => date('Y-m-d H:i')]
                    ], 'integral_add'); //

                }
            } catch (Exception $exception) {
                $packageOrderModel->rollback();
                file_put_contents('./log/' . date('Y-m-d') . 'packageerrorlog.txt', $exception->getMessage() . PHP_EOL, FILE_APPEND);
                $packageOrderModel->where(['order_sn' => $out_trade_no])->update(['status' => 1]);
                return \json([
                    "code" => "FAIL",
                    "message" => "失败"
                ]);
            }

            return \json([
                "code" => "SUCCESS",
                "message" => "成功"
            ]);
        }
    }
    public function rechargeNotify(Request $request)
    {
        $getCallBackJson = file_get_contents('php://input');
        file_put_contents('./log/'  . date('Y-m-d') . 'recharge.txt', $getCallBackJson . PHP_EOL, FILE_APPEND);
        $getCallBackArray = json_decode($getCallBackJson, true);
        $associatedData = $getCallBackArray['resource']['associated_data'];
        $nonceStr = $getCallBackArray['resource']['nonce'];
        $ciphertext = $getCallBackArray['resource']['ciphertext'];
        $ciphertext = \base64_decode($ciphertext);
        $ctext = substr($ciphertext, 0, -16);
        $authTag = substr($ciphertext, -16);
        $str = \openssl_decrypt($ctext, 'aes-256-gcm', Config::getConfigValue('apikey'), \OPENSSL_RAW_DATA, $nonceStr, $authTag, $associatedData);
        $result = json_decode($str, true);;
        if ($result['trade_state'] == 'SUCCESS') {
                $out_trade_no = $result['out_trade_no'];
                $pay_money = bcdiv($result['amount']['total'], 100, 2);

                $RechargeModel = new Recharge();
                $rechargeInfo = $RechargeModel->where(['sn_order' => $out_trade_no])->find();
                if ($pay_money !=  $rechargeInfo['amount']){
                    return \json([
                        "code" => "FAIl",
                        "message" => "失败"
                    ]);
                }
                if ($rechargeInfo['status'] != 1) {
                    return \json([
                        "code" => "FAIL",
                        "message" => "失败"
                    ]);
                }

                $RechargeModel->where(['sn_order' => $out_trade_no,'id' => $rechargeInfo['id']])->update(['status' => 2]);
                try {
                    $RechargeModel->startTrans();
                    $userModel = new User();
                    $userInfo = $userModel->where(['id' => $rechargeInfo['uid']])->find();
                    $userModel->where(['id' => $rechargeInfo['uid']])
                        ->inc('balance', (float)bcadd($pay_money, $rechargeInfo['give_amount'], 2))->inc('recharge_amount', $pay_money)->update();
                    $amountLog = new AmountLog();
                    $amountLog->insert([
                        'amount' => $pay_money,
                        'pay_method' => 1,
                        'order_id' => $rechargeInfo['id'],
                        'order_sn' => $out_trade_no,
                        'operate_type' => 1,
                        'pay_type' => 3,
                        'create_time' => time(),
                        'ratio' => 1,
                        'type' => 1,
                        'uid' => $rechargeInfo['uid'],
                        'give_amount' => $rechargeInfo['give_amount'],
                    ]);
                    $RechargeModel->where(['sn_order' => $out_trade_no,'id' => $rechargeInfo['id']])->update(['status' => 3, 'update_time' => time()]);

                    $RechargeModel->commit();
                } catch (Exception $exception) {

                    $RechargeModel->rollback();
                    file_put_contents('./log/' . date('Y-m-d') . 'rechargeerrorlog.txt', $exception->getMessage() . PHP_EOL, FILE_APPEND);
                    $RechargeModel->where(['sn_order' => $out_trade_no,'id' => $rechargeInfo['id']])->update(['status' => 1]);

                    return \json([
                        "code" => "FAIL",
                        "message" => "失败"
                    ]);
                }
            $messageModel = new MessageTemplate();
            $messageModel->sendMessage($userInfo['openid'], [
                'thing2' => ['value' => '微信充值'],
                'amount8' => ['value' => $pay_money],
                'amount6' => ['value' => bcadd($userInfo['balance'], bcadd($pay_money, $rechargeInfo['give_amount'], 2), 2)],
                'time4' => ['value' => date('Y-m-d  H:i')],
            ], 'balance_add'); // 余额变动
            if ($userInfo['phone']){
                $messageModel->sendAliMessage($userInfo['phone'],'balance_add',[
                    'desc'=> '余额充值',
                    'money'=> $pay_money,
                ]);;
            }
                return \json([
                    "code" => "SUCCESS",
                    "message" => "成功"
                ]);
            }

    }
    protected function getRandCode($num = 6)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
        $str = '';
        for ($i = 0; $i < $num; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        $userModel = new User();
        $user = $userModel->where(['invite_code' => $str])->find();
        if ($user) {
            self::getRandCode($num);
        }
        return $str;
    }
    public function goodsReturns(Request $request)
    {
        $info = $request->header();
        $inWechatpaySignature = $info['wechatpay-signature'];
        $inWechatpayTimestamp = $info['wechatpay-timestamp'];
        $inWechatpaySerial = $info['wechatpay-serial'];
        $inWechatpayNonce = $info['wechatpay-nonce'];
        if (!$inWechatpaySignature or !$inWechatpayTimestamp or !$inWechatpaySerial or !$inWechatpayNonce) {
            header("Location:/404.html");
            exit;
        }

        $inBody = file_get_contents("php://input");// 请根据实际情况获取，例如: file_get_contents('php://input');
        $apiv3Key = Config::getConfigValue('apikey');// 在商户平台上设置的APIv3密钥
        // 根据通知的平台证书序列号，查询本地平台证书文件，这里是自己生成的证书
        $platformPublicKeyInstance = Rsa::from(Config::getConfigValue('key_file'), Rsa::KEY_TYPE_PUBLIC);
        // 检查通知时间偏移量，允许5分钟之内的偏移
        $timeOffsetStatus = 300 >= abs(Formatter::timestamp() - (int)$inWechatpayTimestamp);
        $verifiedStatus = Rsa::verify(
        // 构造验签名串
            Formatter::joinedByLineFeed($inWechatpayTimestamp, $inWechatpayNonce, $inBody),
            $inWechatpaySignature,
            $platformPublicKeyInstance
        );
        if ($timeOffsetStatus && $verifiedStatus) {
            // 转换通知的JSON文本消息为PHP Array数组
            $inBodyArray = (array)json_decode($inBody, true);
            // 使用PHP7的数据解构语法，从Array中解构并赋值变量
            ['resource' => [
                'ciphertext' => $ciphertext,
                'nonce' => $nonce,
                'associated_data' => $aad
            ]] = $inBodyArray;
            // 加密文本消息解密
            $inBodyResource = AesGcm::decrypt($ciphertext, $apiv3Key, $nonce, $aad);
            // 把解密后的文本转换为PHP Array数组
            $inBodyResourceArray = (array)json_decode($inBodyResource, true);
            // print_r($inBodyResourceArray);// 打印解密后的结果
            $result = $inBodyResourceArray;
            file_put_contents('./log/' . date('Y-m-d') . 'goodsReturns.txt', $result . PHP_EOL, FILE_APPEND);
            if ($result['refund_status'] == 'SUCCESS') {
                $out_trade_no = $result['out_trade_no'];
                $goodsOrder = new GoodsOrder();
                $goodsOrderInfo = $goodsOrder->where(['sn_order' => $out_trade_no])->find();
                if ($goodsOrderInfo['status' != 5]) {
                    return \json([
                        "code" => "SUCCESS",
                        "message" => "成功"
                    ]);
                }
                $goodsOrder->where(['sn_order' => $out_trade_no])->update(['status' => 7]);
                if ($goodsOrderInfo['user_coupon_id']) {
                    $userCouponModel = new UserCoupon();
                    $userCouponModel->where(['id' => $goodsOrderInfo['user_coupon_id']])->update(['status' => 1]);
                }
                $point = bcmul($goodsOrderInfo['point_deduction_amount'], $goodsOrderInfo['point_deduction_ratio'], 2);
                if ($point) {
                    $IntegralLogModel = new IntegralLog();
                    $userNeedIntegralData = [
                        'mode_type' => 7,
                        'type' => 1,
                        'deduction_ratio' => $goodsOrderInfo['point_deduction_ratio'],
                        'num' => $point,
                        'uid' => $goodsOrderInfo['user_id'],
                        'create_time' => time(),
                        'order_id' => $goodsOrderInfo['id']
                    ];
                    $IntegralLogModel->insert($userNeedIntegralData);
                    $userModel = new User();
                    $userModel->where(['id' => $goodsOrderInfo['user_id']])->inc('surplus_integral', $point)->update();
                    $AmountLogData = [  // 金额扣除记录
                        'uid' => $request->userInfo['id'],
                        'amount' => $goodsOrderInfo['reality_amount'],
                        'create_time' => time(),
                        'operate_type' => 18,
                        'pay_type' => 3,
                        'pay_method' => 1,
                        'order_id' => $goodsOrderInfo['id'],
                        'ratio' => 1,
                        'type' => 2,
                        'order_sn'=> $out_trade_no,
                    ];
                    $amountLogModel = new AmountLog();
                    $amountLogModel->insert($AmountLogData);
                }
                $userModel->where(['id' => $goodsOrderInfo['user_id']])
                    ->dec('consumption_amount', $goodsOrderInfo['reality_amount'])->update();
            }
        }
        exit;
    }
    public function sign(Request $request)
    {
        $param = $request->param();
        $url = $param['url'];
        $offiaccount = new Offiaccount();
        $ticket = $offiaccount->getWxTicket();

        $params = [
            //'appId' => \app\index\model\Config::getConfigValue('appid'),
            'timestamp' => (string)Formatter::timestamp(),
            'noncestr' => Formatter::nonce(),
            'jsapi_ticket' => $ticket['ticket'],
            'url' => $url,
        ];
        ksort($params);
        $string = urldecode(http_build_query($params));
        $signature = sha1($string);
        $params['appId'] =\app\home\model\Config::getConfigValue('appid');
        $params['string'] = $string;
        $params['sign'] = $signature;

        return adminSuccess('微信参数', $params);
    }
    public function send()
    {
        $user =new User();

        $userInfo = $user->where(['id' => 1])->find();
        $messageModel = new MessageTemplate();
        $infn = $messageModel->sendAliMessage(15575392041,'balance_sub',[
                'platform'=> Config::getConfigValue('system_name'),
                'name'=> '余额消费',
                'money'=> 1000,
            ]);;

        var_dump($infn);exit;
    }

 /*   public function bargainingPayNotify(Request $request){
        $getCallBackJson = file_get_contents('php://input');
        file_put_contents('./log/' . date('Y-m-d') . 'goodsdata.txt', $getCallBackJson . PHP_EOL, FILE_APPEND);
        $getCallBackArray = json_decode($getCallBackJson, true);
        $associatedData = $getCallBackArray['resource']['associated_data'];
        $nonceStr = $getCallBackArray['resource']['nonce'];
        $ciphertext = $getCallBackArray['resource']['ciphertext'];
        $ciphertext = \base64_decode($ciphertext);
        $ctext = substr($ciphertext, 0, -16);
        $authTag = substr($ciphertext, -16);
        $str = \openssl_decrypt($ctext, 'aes-256-gcm', Config::getConfigValue('apikey'), \OPENSSL_RAW_DATA, $nonceStr, $authTag, $associatedData);
        $result = json_decode($str, true);;
        if ($result['trade_state'] == 'SUCCESS') {
            $out_trade_no = $result['out_trade_no'];
            $pay_money = bcdiv($result['amount']['total'], 100, 2);
            $BargainingOrderModel = new  BargainingOrder();
            $goodsOrderInfo = $BargainingOrderModel->where(['sn_order' => $out_trade_no])->find();
            if ($pay_money !=$goodsOrderInfo['reality_amount'] ){
                return \json([
                    "code" => "FAIL",
                    "message" => "支付金额有误"
                ]);
            }
            if ($goodsOrderInfo['status'] != 1) {
                return \json([
                    "code" => "FAIL",
                    "message" => "失败"
                ]);
            }
            $BargainingOrderModel->where(['sn_order' => $out_trade_no])->update(['status' => 2]);
            try {
                $BargainingOrderModel->startTrans();
                $amountLog = new AmountLog();
                $amountLog->insert([
                    'amount' => $pay_money,
                    'pay_method' => 1,
                    'order_id' => $goodsOrderInfo['id'],
                    'operate_type' => 29,
                    'pay_type' => 5,
                    'create_time' => time(),
                    'ratio' => 1,
                    'uid' => $goodsOrderInfo['user_id'],
                    'type' => 2,
                    'order_sn' => $goodsOrderInfo['sn_order'],
                    'status' => 0,

                ]);
                if ($goodsOrderInfo['take_over_way'] == 2) {
                    $BargainingOrderModel->where(['sn_order' => $out_trade_no])->update(['status' => 3, 'update_time' => time()]);
                } else {
                    $BargainingOrderModel->where(['sn_order' => $out_trade_no])->update(['status' => 4, 'update_time' => time()]);
                }
                $BargainingOrderModel->commit();

            } catch (Exception $exception) {
                $BargainingOrderModel->rollback();
                file_put_contents('./' . date('Y-m-d') . 'paylogerror.txt', $exception->getMessage() . PHP_EOL, FILE_APPEND);
                $BargainingOrderModel->where(['sn_order' => $out_trade_no])->update(['status' => 1]);
                return \json([
                    "code" => "FAIL",
                    "message" => "失败"
                ]);
            }
            return \json([
                "code" => "SUCCESS",
                "message" => "成功"
            ]);
        }
    }*/



}